//
//  PPShareTemplateController.m
//  pickpic
//
//  Created by 胡文广 on 2017/3/22.
//  Copyright © 2017年 MicroDream. All rights reserved.
//

typedef enum : NSUInteger {
    PPShareTemplateTypeNone = 1,
    PPShareTemplateTypeEbook = 2,
} PPShareTemplateType;

#import "PPShareTemplateController.h"
#import "PPHomeAlbumModel.h"
#import "UIImage+ImageEffects.h"
#import "PPSocializationManager.h"
#import "PPTemplateViewController.h"
#import "PPBaseNavigationViewController.h"
#import "UIImage+Resize.h"
#import "PPPhotoBrowserController.h"
#import "PPTemplateModel.h"
#import "PPShareView.h"
#import "PPTemplateCoverFrame.h"
#import "NSTimer+PPTimer.h"
#import "PPEbookAlbum.h"
#import "PPAlbumModel.h"
#import "PPHomeEbookModel.h"
#import "PPCoverAlertView.h"

@interface PPShareTemplateController ()<PPTemplateViewControllerDelegate>
@property (weak, nonatomic) IBOutlet PPShareView *fullImageView;
//@property (weak, nonatomic) IBOutlet UIImageView *albumImageView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
//@property (nonatomic,strong) UIImageView *userIcon;
//@property (nonatomic,strong) UILabel *userPickLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *shareTitleLeft;

//@property (nonatomic,strong) UILabel *centerLabel;

@property (nonatomic,assign) PPShareTemplateType shareTemplateType;
@property (nonatomic,strong) PPTemplateModel *shareTemplateModel;

@property (nonatomic,strong) UIView *progressView;
@property (nonatomic,strong) UILabel *progressLabel;

@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign) BOOL isProgress;
@property (nonatomic,strong) JCDownloadOperation *operation;

//相册图片id
@property (nonatomic,strong) NSMutableArray *albumpictureIds;
//相册图片URL(含封面)
@property (nonatomic,strong) NSMutableArray *albumpictureURLs;
//相册下载的图片
@property (nonatomic,strong) NSMutableArray *ebookImages;

//相册 (不含封面)
@property (nonatomic,strong) NSMutableArray *pictureURLs;

@property (nonatomic,assign) BOOL isEdit;

@property (weak, nonatomic) IBOutlet UIButton *image1;
@property (weak, nonatomic) IBOutlet UIButton *image2;
@property (weak, nonatomic) IBOutlet UIButton *image3;
@property (weak, nonatomic) IBOutlet UIButton *image4;

@property (nonatomic,strong) NSOperationQueue *operationQueue;

@property (nonatomic,assign) CGFloat date;


@property (nonatomic,strong) NSDictionary *shareInfo;

@property (nonatomic,assign) BOOL picFinish;

@property (nonatomic,strong) SDWebImageDownloader *manager;

///MARK:处理原图
//相册图片id
@property (nonatomic,strong) NSMutableArray *albumpictureIdsOrg;
//相册图片URL(含封面)
@property (nonatomic,strong) NSMutableArray *albumpictureURLsOrg;
//相册下载的图片
@property (nonatomic,strong) NSMutableArray *ebookImagesOrg;

@property (nonatomic,strong) NSMutableArray *eBookModelsOrg;

//生成结果
@property (nonatomic,assign) BOOL updateEbook;

@property (nonatomic,strong) PPHomeAlbumModel *shareAlbumModel;

@property (nonatomic,strong)PPCoverAlertView *coverAlert;
@property (nonatomic,strong) UIView *coverView;

@property (nonatomic,assign) CGFloat progressFloat;

@end

@implementation PPShareTemplateController
- (PPHomeAlbumModel *)shareAlbumModel{

    if (!_shareAlbumModel) {
        _shareAlbumModel = [[PPHomeAlbumModel alloc] init];
    }
    return _shareAlbumModel;
}
- (NSMutableArray *)pictureURLs{

    if (!_pictureURLs) {
        
        _pictureURLs = [NSMutableArray array];
    }
    return _pictureURLs;
}
- (NSMutableArray *)albumpictureURLs{

    if (!_albumpictureURLs) {
        
        _albumpictureURLs = [NSMutableArray array];
    }
    return _albumpictureURLs;
}
- (NSMutableArray *)ebookImages{

    if (!_ebookImages) {
        _ebookImages = [NSMutableArray array];
    }
    return _ebookImages;
}

- (NSMutableArray *)albumpictureIds{

    if (!_albumpictureIds) {
        _albumpictureIds = [NSMutableArray array];
    }
    return _albumpictureIds;
}
- (UILabel *)progressLabel{

    if (!_progressLabel) {
        _progressLabel = [[UILabel alloc] init];
        _progressLabel.textAlignment = NSTextAlignmentLeft;
        _progressLabel.font = [UIFont systemFontOfSize:12.0f];
        _progressLabel.text = @"生成中";
        _progressLabel.textColor = WHITE;
        _progressLabel.frame = CGRectMake(self.progressView.width, SCREEN_HEIGHT - self.bottomViewConstraint.constant-21, 40, 21);
    }
    return _progressLabel;
}
- (UIView *)progressView{

    if (!_progressView) {
        _progressView = [[UIView alloc] init];
        _progressView.backgroundColor = COLORA(255, 221,23);
        _progressView.frame = CGRectMake(0,SCREEN_HEIGHT - self.bottomViewConstraint.constant, 1, 2);
    }
    return _progressView;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    [self.navigationController setNavigationBarHidden:YES animated:animated];

}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
}
#pragma mark -获取图片信息列表
- (void)allAlbumpictureIds{
    if (self.eBookTemplateModel) {
        //取上一次生成的电子书信息
        for (PPHomeEbookModel *ebookM in self.eBookModels) {
            [self.albumpictureIds addObject:ebookM.pictureId];
            [self.albumpictureURLs addObject:[NSString stringWithFormat:@"%@%@",self.homeAlbumModel.coverHost,ebookM.url]];
        }
        
        if (self.albumpictureURLs.count > 0) {
            [self downAllAlbumImage:NO];
        }
        
    }else{
        [self downloadAlbum];
    }
}

- (void)downAllAlbumImage:(BOOL)push{

    
    self.ebookImages = [NSMutableArray array];

    NSMutableArray *temp = [NSMutableArray array];
//    //下载所有图片
    dispatch_group_t group =dispatch_group_create();
    for (int i = 0; i <  self.albumpictureURLs.count; i ++)
    {
        PPLog(@"下载电子书图片=%@",self.albumpictureURLs[i]);
        
        dispatch_group_enter(group);
        self.manager = [SDWebImageDownloader sharedDownloader];

        self.manager.maxConcurrentDownloads = 1;
        [self.manager downloadImageWithURL:[NSURL URLWithString:self.albumpictureURLs[i]] options:SDWebImageDownloaderIgnoreCachedResponse progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            if (image) {
//                [self.ebookImages addObject:image];

                NSDictionary *dict = @{
                                       @"url":self.albumpictureURLs[i],
                                        @"img":image,
                                       };
                
                
//                PPLog(@"加进来的%@",[NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",self.albumpictureURLs[i]]);
                [temp addObject:dict];
            }
              PPLog(@"下载完成或失败了,imgs,imgs.count %zd",temp.count);
            if (finished) {
                dispatch_group_leave(group);
            }
        }];
    }
    dispatch_group_notify(group,dispatch_get_main_queue(), ^(){
        
        if (self.albumpictureURLs.count != temp.count) {
            PPLog(@"图片下载有问题");
            [self downAllAlbumImage:push];
            return ;
        }
        
        self.picFinish = YES;
        
        for (NSString *strUrl in self.albumpictureURLs) {
//            NSString* key = [NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",strUrl];
            NSString* key = strUrl;
            for (NSDictionary *dict in temp) {
                if ([dict[@"url"] isEqualToString:key]) {

               PPLog(@"图片下载%@ - %@",strUrl,dict[@"url"]);
                    [self.ebookImages addObject:dict[@"img"]];
                    break;
                }
            }
        }
//        [self.image1 setImage:self.ebookImages[0] forState:UIControlStateNormal];
//         [self.image2 setImage:self.ebookImages[1] forState:UIControlStateNormal];
//         [self.image3 setImage:self.ebookImages[2] forState:UIControlStateNormal];
//         [self.image4 setImage:self.ebookImages[3] forState:UIControlStateNormal];
        
        
        if (push) {
            [self createPicpathWithuuids:self.albumpictureIds templateModel:self.shareTemplateModel uploadImages:self.ebookImages update:true];
        }
        

    });

}
- (void)popViewPreviousController{
    self.fullImageView.alpha = 1;
    self.bottomView.alpha = 1;
    [UIView animateWithDuration:0.2 animations:^{
        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH,self.bottomViewConstraint.constant);
        self.fullImageView.alpha = 0.5;
    } completion:^(BOOL finished) {
        [[SDWebImageDownloader sharedDownloader] cancelAllDownloads];
        [self.navigationController popViewControllerAnimated:NO];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (IS_IPHONE_5) {
        self.shareTitleLeft.constant = 14;
    }
    
    
    //下载相册图片
//    [self downloadAlbumListOrg];
    
    //获取分享信息
//    self.shareInfo = @{
//                       @"title":self.albumModel.title,
//                       @"title2":self.albumModel.title2,
//                       @"url":self.albumModel.url,
//                       @"image":self.albumModel.image,
//                       };
//    
//    PPLog(@"分享URL = %@",self.albumModel.url);
    //    NSMutableDictionary *shareDict = [NSMutableDictionary dictionary];
    //    [shareDict setSafeObject:self.normalAlbumModel.title forKey:@"title"];
    //    [shareDict setSafeObject:self.normalAlbumModel.title2 forKey:@"title2"];
    //    [shareDict setSafeObject:self.normalAlbumModel.url forKey:@"url"];
    //    [shareDict setSafeObject:self.normalAlbumModel.coverImage forKey:@"image"];
    //    self.shareInfo = shareDict;
    
//    [self allAlbumpictureIds];
    
//    [self setViewAttribute];
    
    //设置分享封面
    [self setShareCoverInfo:NO];
    
//    if (self.eBookModel) {
        PPLog(@"带有模板的电子书");
//        self.shareTemplateType = PPShareTemplateTypeEbook;
//        self.shareTemplateModel = self.eBookModel;
//        self.albumModel.image = self.eBookCoverImage;
//        [self createShareView:self.shareTemplateModel];
        
//    }else{
        PPLog(@"默认电子书");
//        self.albumModel.image = self.coverImage;
//        self.shareTemplateType = PPShareTemplateTypeNone;
//         [self createShareView:self.shareTemplateModel];
//    }
    
    self.view.backgroundColor = WHITE;
    self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH,self.bottomViewConstraint.constant);
    [UIView animateWithDuration:.5 animations:^{
        self.bottomView.frame = CGRectMake(0,SCREEN_HEIGHT-self.bottomViewConstraint.constant - 64, SCREEN_WIDTH, self.bottomViewConstraint.constant);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAlbumPic:) name:PPNotice_ChangeAlbumsPic object:nil];
    
    self.fullImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(previewAlbum)];
    [self.fullImageView addGestureRecognizer:tapRec];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAlbumDesc:) name:PPNotice_ChangeAlbumsDesc object:nil];

    [self showCoverView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTitle:) name:PPAlbumChanageTitle object:nil];
}
- (void)changeTitle:(NSNotification *)notice{
    
    if (notice.object) {
//        [self.fullImageView updateCoverTitle:notice.object];
        self.normalAlbumModel.title = notice.object;
        
         [self setShareCoverInfo:NO];
        
        
    }

}
- (PPCoverAlertView *)coverAlert{
    
    if (!_coverAlert) {
        _coverAlert = [PPCoverAlertView coverAlertView];
        WEAKSELF
        _coverAlert.BlockClick = ^{
            
            [weakSelf.coverView removeFromSuperview];
            
        };
    }
    return _coverAlert;
}
#pragma mark -Cover
- (void)showCoverView{
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"saveFirst"] boolValue]) {
    
            self.coverView = [[UIView alloc] init];
            self.coverView .frame = CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            self.coverView .backgroundColor = [UIColor colorWithWhite:0.f alpha:0.7];
            UIImageView *img = [[UIImageView alloc] init];
            img.userInteractionEnabled = YES;
            img.center = CGPointMake(self.navigationController.view.center.x, self.navigationController.view.center.y-45 - 30-7);
            img.bounds = CGRectMake(0, 0, 220, 45);
            img.image = [UIImage imageNamed:@"ebookToastView"];
            self.coverAlert.leftLabel.text = @"可以点击封面进行预览";
            self.coverAlert.frame = CGRectMake(10,5,200, 30);
            [img addSubview:self.coverAlert];
            
            [self.coverView addSubview:img];
            [self.navigationController.view addSubview: self.coverView];
            
            [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"saveFirst"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }

}
#pragma mark -设置分享页封面
- (void)setShareCoverInfo:(BOOL)isNormal{
    self.shareTemplateType = PPShareTemplateTypeNone;
    self.fullImageView.shareType = PPShareTemplateTypeNone;
    self.fullImageView.albumModel = self.normalAlbumModel;
    
    if (self.normalAlbumModel.ebookPictures.count > 0) {
        self.shareTemplateType = PPShareTemplateTypeEbook;
        self.fullImageView.shareType = PPShareViewTypeEbook;
        if (self.eBookTemplateModel && !isNormal) {
            if (self.normalAlbumModel.eBookCoverImage == nil) {
                self.normalAlbumModel.eBookCoverImage = self.normalAlbumModel.coverImage;
            }
            
            self.fullImageView.albumModel = self.normalAlbumModel;
            self.fullImageView.tempModel = self.eBookTemplateModel;
            self.shareTemplateModel = self.eBookTemplateModel;
        }
    }
    self.fullImageView.BlockTapPhotoView = ^{
        [self previewAlbum];
    };
}
#pragma mark -编辑了第几张图片
- (void)changeAlbumPic:(NSNotification *)notice{

    NSDictionary *dic = notice.object;
    
    if (dic) {

        for (int i = 0; i<self.normalAlbumModel.ebookPictures.count; i++) {
            PPPictureModel *picM = self.normalAlbumModel.ebookPictures[i];
            if (dic[@"pictureid"] == picM.picID && picM.picType == [dic[@"picType"] integerValue]) {
                picM.picKey = dic[@"url"];
                picM.picURL = [NSString stringWithFormat:@"%@%@",picM.picHost,picM.picKey];
                
                if (picM.picType == PPPictureTypeCover) {
                    [self.fullImageView updateCoverImage:dic[@"img"]];
                }
                
            }
        }
    }
//    if ([dic[kCutPicKey] integerValue] == 0) {
//        [self.fullImageView updateCoverImage:dic[kCutPicValue]];
//    }
//    
//    PPLog(@"点击了第几个%zd",[dic[kCutPicKey] integerValue]);
//
//    if (self.ebookImages.count <= 0 ||[dic[kCutPicKey] integerValue] >= self.ebookImages.count) {
//        
//        PPLog(@"修改越界");
//        return;
//    }
//    
//    
//    [self.ebookImages replaceObjectAtIndex:([dic[kCutPicKey] integerValue]) withObject:dic[kCutPicValue]];
        
        
//    }
    
    
//    switch ([dic[kCutPicKey] integerValue]) {
//        case 0:
//            [self.image1 setImage:self.ebookImages[0] forState:UIControlStateNormal];
//            break;
//        case 1:
//            [self.image2 setImage:self.ebookImages[1] forState:UIControlStateNormal];
//            
//            break;
//        case 2:
//            [self.image3 setImage:self.ebookImages[2] forState:UIControlStateNormal];
//            
//            break;
//        case 3:
//            [self.image4 setImage:self.ebookImages[3] forState:UIControlStateNormal];
//            
//            break;
//            
//        default:
//            break;
//    }
//    }
}
- (NSTimer *)timer{

    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    }
    return _timer;
}
- (void)setViewAttribute{
    
//    if (!self.normalAlbumModel.ebookPictures.count) {
//        self.fullImageView.image = [self.normalAlbumModel.coverImage blurryImagewithBlurLevel:50];
//        
//    }
//    self.fullImageView.BlockTapPhotoView = ^{
//        [self previewAlbum];
//    };
//    if ([self.albumModel.title isValid]){
//        NSString *albumTitle = self.normalAlbumModel.title;
//        self.albumModel.title = albumTitle;
//    }
//
//    if (DGCurrentAccount.profiles.avatarURLString) {
//        self.albumModel.userUrl = DGCurrentAccount.profiles.avatarURLString;
//    }else{
//        self.albumModel.image = [UIImage imageNamed:@"icon-person-150"];
//    }
//    
//    PPAccountProfiles *profiles = [PPAccountManager sharedInstance].account.profiles;
//    self.albumModel.nickName = profiles.name;
//    self.albumModel.pickpic = [NSString stringWithFormat:@"pickpic号：%@",DGCurrentAccount.pickpic];;
//    
////    if (!self.eBookModel) {
////        self.fullImageView.shareType = PPShareViewTypeNone;
////        self.fullImageView.albumModel.image = self.coverImage;
////        self.fullImageView.albumModel = self.albumModel;
////    }
//    
//    
//    if (self.normalAlbumModel.ebookPictures.count > 0) {
//        self.fullImageView.shareType = PPShareViewTypeNone;
//        self.fullImageView.albumModel.image = self.normalAlbumModel.coverImage;
//        self.fullImageView.albumModel = self.albumModel;
//    }
    
}

- (IBAction)dismissViewController:(id)sender {
    
    [self popViewPreviousController];

}

#pragma mark -点击分享页面的封面图
- (void)previewAlbum/*:(UITapGestureRecognizer *)rec*/{
    if(self.shareTemplateType == PPShareTemplateTypeNone){
        /// 获取相册 - 图片- 相册描述 - 相册
        PPPhotoBrowserController *browserVc = [[PPPhotoBrowserController alloc] init];
        browserVc.type = PPPhotoBrowserTypeAlbumNone;
        browserVc.albumModel = self.albumM;
        browserVc.albumHomeModel = self.normalAlbumModel;
        [self.navigationController pushViewController:browserVc animated:YES];
    }else{
 
        PPPhotoBrowserController *browserV = [[PPPhotoBrowserController alloc] init];
        browserV.type = PPPhotoBrowserTypeEbook;
        browserV.templateM = self.shareTemplateModel;
        browserV.albumModel = self.albumM;
        browserV.albumHomeModel = self.normalAlbumModel;
        [self.navigationController pushViewController:browserV animated:YES];

        
        
/*
        if(self.isProgress){ return ;}
        
    // 获取相册 - 图片- 相册描述 - 相册
            PPPhotoBrowserController *browserVc = [[PPPhotoBrowserController alloc] init];
            browserVc.type = PPPhotoBrowserTypeEbook;
            //封面data模型+frame模型
//            -self.albumModel.url = self.shareTemplateModel.url7;
//            self.albumModel.photoFrameImage = self.shareTemplateModel.coverImg;
        
//           - self.albumModel.photoFrameImage =  [UIImage imageWithData:[[NSData alloc] initWithBase64EncodedString:self.shareTemplateModel.coverImgString options:(NSDataBase64DecodingIgnoreUnknownCharacters)]];
//        
//            -PPHomeAlbumModel *coverModel = self.albumModel;
        
        if(self.albumpictureURLs.count <= 0){
            [self.navigationController.view toastMessage:@"正在加载相册信息,请稍等！" duration:1.f];
            return;
        }
//          -  coverModel.coverURL = self.albumpictureURLs[0];
//        
//           - coverModel.orderNum = self.shareTemplateModel.orderNum;
//            -self.shareTemplateModel.coverFrameM.coverModel = coverModel;
        
            browserVc.BlockSaveEbookInfo = ^{
                self.progressLabel.text = @"更新中";
                
                if(self.ebookImages.count <= 0){
                
                    [self.ebookImagesOrg enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [self.ebookImages addObject:obj];
                    }];
                }

                if(self.ebookImages.count <= 0){
                    [self.navigationController.view toastMessage:@"正在加载相册信息,请稍等！" duration:1.f];
                    return ;
                }
                
                self.updateEbook = YES;
                
                [self progressViewCreate];
                
                
                [self createPicpathWithuuids:self.albumpictureIds templateModel:self.shareTemplateModel uploadImages:self.ebookImages update:false];
            };
            browserVc.templateM = self.shareTemplateModel;
            browserVc.albumModel = self.albumM;
//            browserVc.albumCoverModel = self.shareTemplateModel.coverFrameM.coverModel;

//            browserVc.innerImageURLs = self.pictureURLs;
        
            browserVc.ebookAlbums = self.eBookModels;
        
        
            [self.navigationController pushViewController:browserVc animated:YES];
        */
    }
}
///MARK:模板列表
- (IBAction)selectTemplate:(id)sender {
    PPTemplateViewController *templateVc = [[PPTemplateViewController alloc] init];
    templateVc.delegate = self;
//-    templateVc.albumCoverModel = self.albumModel;
    templateVc.albumM = self.albumM;
    [self.navigationController pushViewController:templateVc animated:YES];
}

- (void)shareThird{
    
     [[PPSocializationManager sharedInstance] shareTitle:[self.shareInfo objectForKey:@"title"]  subtitle:[self.shareInfo objectForKey:@"title2"] url:[self.shareInfo objectForKey:@"url"] image:[self.shareInfo objectForKey:@"image"] thumbnail:nil type:[[self.shareInfo objectForKey:@"type"] integerValue]];
}
- (IBAction)shareInfo:(id)sender {
    
    if (self.shareInfo) {
        [self shareThird];
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    [PPNetworkService getShareInfoWithAlbumID:self.normalAlbumModel.albumID callback:^(id data, NSError *error) {

        PPLog(@"%@",data);
        
        if (error == nil) {
            NSString *sort;
            UIButton *btn = (UIButton *)sender;
            if(self.normalAlbumModel.order == PPAlbumOrderDesc) {
                sort = @"asc";
            } else {
                sort = @"desc";
            }
            NSString *shareURL = [NSString stringWithFormat:@"%@&order=%@",data[@"url"],sort];
            
            NSString *title2 = data[@"title2"];
            
            if (title2.length <= 0) {
                title2 = @"分享自PickPic";
            }
            
            NSMutableDictionary *shareDict = [NSMutableDictionary dictionary];
            [shareDict setSafeObject:data[@"title"] forKey:@"title"];
            [shareDict setSafeObject:title2 forKey:@"title2"];
            [shareDict setSafeObject:shareURL forKey:@"url"];
            [shareDict setSafeObject:self.normalAlbumModel.coverImage forKey:@"image"];
            [shareDict setSafeObject:@(btn.tag) forKey:@"type"];
            self.shareInfo = shareDict;
            [self shareThird];
            [hud hide:YES];
        }else{
            [hud hide:YES];
            [self.navigationController.view toastMessage:error.networkPrompt];
        }
        
        
    }];
    
    
    
    

    
//
    
//    http://h5.pickpic.zhsit.cn/Admin-v1/web/share.html?id=234&udid=696fec50-95ee-4f7a-a37b-750b6971b456&order=asc
    
    

    
    
//    NSArray *array = [self.shareInfo[@"url"] componentsSeparatedByString:@"&"];
//    
//    if (array.count > 1) {
//        
//        NSString *shareURL = [NSString stringWithFormat:@"%@&order=%@&%@",array[0],sort,array[1]];
//        PPLog(@"%@",shareURL);
//         [[PPSocializationManager sharedInstance] shareTitle:self.shareInfo[@"title"] subtitle:self.shareInfo[@"title2"] url:shareURL image:self.shareInfo[@"image"] thumbnail:nil type:btn.tag];
//        
//    }else{
    
//        NSString *shareURL = [NSString stringWithFormat:@"%@&order=%@",self.shareInfo[@"url"],sort];
//    
//    NSString *title2 = self.shareInfo[@"title2"];
//    
//    if (title2.length <= 0) {
//        title2 = @"分享自PickPic";
//    }
//        [[PPSocializationManager sharedInstance] shareTitle:self.shareInfo[@"title"] subtitle:title2 url:shareURL image:self.shareInfo[@"image"] thumbnail:nil type:btn.tag];
//    }
    
    

}
//- (NSMutableDictionary *)reloadData {
//    NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid" : self.albumM.auuid, @"deleted" : @(NO)}];
//    
//    NSArray *sortedImages = nil;
//    if(self.albumM.order.integerValue == PPAlbumOrderDesc) {
//        sortedImages = [images.reverseObjectEnumerator allObjects];
//    } else {
//        sortedImages = images;
//    }
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

//    NSMutableArray *items = [NSMutableArray array];
//    [sortedImages enumerateObjectsUsingBlock:^(PPAlbumImageModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
//        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
//        artwork.uuid = [NSString uuid];
//        PPAbstractArtwork *temp = obj.artwork;
//        artwork.URLString = temp.URLString;
//        
//        [items addObject:artwork.URLString];
//        
//        if([self.albumM.coverURLString rangeOfString:temp.URLString].location !=NSNotFound){
//            //封面
//            [items insertObject:artwork.URLString atIndex:0];
//        }
//    }];
    
    
//    [dict setValue:self.albumpictureURLs forKey:@"imgs"];
//
//    [dict setValue:self.albumpictureIds forKey:@"pictureIds"];
//    
//    
//    return dict;
//}

- (void)createShareView:(PPTemplateModel *)templateModel{

    //生成模板
    self.fullImageView.shareType = self.shareTemplateType==PPShareViewTypeNone?PPShareViewTypeNone:PPShareViewTypeEbook;
    
    if (self.shareTemplateType == PPShareViewTypeNone) {

//        self.fullImageView.image = [self.albumModel.image blurryImagewithBlurLevel:50];

//        self.fullImageView.albumModel = self.albumModel;
    }else{
//-        self.fullImageView.albumModel = self.albumModel;
        self.fullImageView.tempModel = templateModel;
    }
    
}
#pragma mark - 生成电子书对应模板(改造)
- (void)updateEbookMusicAlbumID:(NSNumber *)albumID musicID:(NSInteger)musicId{
    
    [PPNetworkService musicBindEbookWithparams:@{@"ebook_id":albumID,@"music_id":@(musicId)} callback:^(id data, NSError *error) {
    }];


}
- (void)templateViewController:(PPTemplateViewController *)templateVc employEbooktemplateModel:(PPTemplateModel *)templateModel{
    
    [self updateEbookMusicAlbumID:self.albumM.albumID musicID:[templateModel.musicId integerValue]];
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.updateEbook= YES;
        
        [self progressViewCreate];
        
//    });
    
    
    NSMutableArray *pics = [NSMutableArray array];
    
    NSMutableArray *tempEbookPics = [NSMutableArray array];
    
    for (int i = 0; i<self.normalAlbumModel.pictures.count; i++) {
        PPPictureModel *picModel = self.normalAlbumModel.pictures[i];
        NSDictionary *dict = @{
                               @"pictureId":picModel.picID,
                               @"url":picModel.picKey,
                               @"picType":i==0?@(1):@(2),
                               };
        [pics addObject:dict];
        
        
        PPPictureModel *ebookPicModel = [[PPPictureModel alloc] init];
        ebookPicModel.picID = picModel.picID;
        ebookPicModel.picAuuid = picModel.picAuuid;
        ebookPicModel.picKey = picModel.picKey;
        ebookPicModel.picHost = picModel.picHost;
        ebookPicModel.picDesc = picModel.picDesc;
        ebookPicModel.picComment = picModel.picComment;
        ebookPicModel.picLike = picModel.picLike;
        ebookPicModel.picURL = [NSString stringWithFormat:@"%@%@",picModel.picHost,picModel.picKey];
        ebookPicModel.picType = picModel.picType;
        
        if (ebookPicModel.picType == 1) {
            [tempEbookPics insertObject:ebookPicModel atIndex:0];
        }else{
            [tempEbookPics addObject:picModel];
        }
        
    }
    
    NSDictionary *ebookDic = @{
                               @"addOrUpdateTemplate":@(true),
                               @"templateId":templateModel.eBookTemplateId,
                               @"pics":pics,
                               };
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [PPNetworkService createEbookTemplateWithparams:ebookDic progress:^(NSProgress * _Nonnull progress) {
            
            if (progress.fractionCompleted ){
                self.progressFloat = SCREEN_WIDTH*0.3;
                [self.timer resumeTimer];
            }
            
            
        } callback:^(id data, NSError *error) {
            if (!error) {
                PPLog(@"电子相册生成成功 %@",ebookDic);
//                NSMutableArray *templateArr = [NSMutableArray arrayWithContentsOfFile:kTemplatePlist];
                  NSMutableArray *templateArr = [NSKeyedUnarchiver unarchiveObjectWithFile:kTemplatePlist];
                
                if (templateArr.count > 0) {
                    for (int i = 0; i<templateArr.count; i++) {
                        PPTemplateModel *temp;
                        if ([templateArr[i] isKindOfClass:[PPTemplateModel class]]) {
                            temp = (PPTemplateModel *)templateArr[i];
                        }else{
                            temp =  [PPTemplateModel yy_modelWithDictionary:templateArr[i]];
                        }
                        
                        //1. 删除模板对应的上一次生成的 同时 //绑定模板对应相册
                        
                        if([temp.eBookTemplateId isEqualToString:templateModel.eBookTemplateId]){
                            PPEbookAlbum *ebookM = [[PPEbookAlbum alloc] init];
                            ebookM.albumID = self.normalAlbumModel.albumID;
                            ebookM.downloadType = PPTemplateDownLoadTypeEmploy;
                            if(!temp.albums){
                                temp.albums = [NSMutableArray array];
                            }
                            self.shareTemplateModel.coverImgString = temp.coverImgString;
                            templateModel.coverImgString = temp.coverImgString;
//                            [temp.albums addObject:[ebookM yy_modelToJSONObject]];
                            [temp.albums addObject:ebookM];
                            
//                            [templateArr replaceObjectAtIndex:i withObject:[temp yy_modelToJSONObject]];
                            [templateArr replaceObjectAtIndex:i withObject:temp];
                            
                        }else{
                            for (id  albumDict in temp.albums) {
                                PPEbookAlbum *ebookT;
                                if ([albumDict isKindOfClass:[PPEbookAlbum class]]) {
                                    ebookT = albumDict;
                                }else{
                                    ebookT = [PPEbookAlbum yy_modelWithDictionary:albumDict];
                                    
                                }
                                
                                if (ebookT.albumID == self.albumM.albumID) {
                                    [temp.albums removeObject:albumDict];
                                    
//                                    [templateArr replaceObjectAtIndex:i withObject:[temp yy_modelToJSONObject]];
                                     [templateArr replaceObjectAtIndex:i withObject:temp];
                                    break;
                                }
                            }
                        }
                    }
//                    [templateArr writeToFile:kTemplatePlist atomically:YES];
                    [NSKeyedArchiver archiveRootObject:templateArr toFile:kTemplatePlist];
                }
                
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    //                [MBProgressHUD hideHUDForView:self.view animated:YES];
                    if (templateModel.orderNum == 0) {
                        [self.normalAlbumModel.ebookPictures removeAllObjects];
                        self.shareTemplateType = PPShareViewTypeNone;
                        [self setShareCoverInfo:YES];
                    }else{
                        self.shareTemplateType = PPShareTemplateTypeEbook;
                        self.normalAlbumModel.ebookPictures = tempEbookPics;
                        self.eBookTemplateModel = templateModel;
                        self.normalAlbumModel.eBookCoverImage = self.normalAlbumModel.coverImage;
                        [self setShareCoverInfo:NO];
                        
//                        PPPictureModel *cover = self.normalAlbumModel.ebookPictures.firstObject;
//                        [self.image1 setImage:cover.picImage forState:UIControlStateNormal];
                        
                    }
                    
                    [self hiddenPrgoress];
                    self.progressFloat = 0 ;
                    
                    [self modifyMusicID:templateModel.musicId musicUrl:templateModel.musicUrl];
                });
                
            }else{
                PPLog(@"电子相册生成失败 = %@",error);
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                self.updateEbook = NO;
                self.progressFloat = 0 ;
                [self hiddenPrgoress];
                
                [self.navigationController.view toastMessage:@"电子相册生成失败,请重试！" duration:1.f];
                
                [self hiddenPrgoress];
                self.progressFloat = 0 ;
            }
            PPLog(@"%@",kTemplatePlist);
            
        }];

        
    });
    
    
//    [PPNetworkService updateEbookTemplateWithparams:ebookDic callback:^(id data, NSError *error) {
//        if (!error) {
//            PPLog(@"电子相册生成成功 %@",ebookDic);
//            NSMutableArray *templateArr = [NSMutableArray arrayWithContentsOfFile:kTemplatePlist];
//       
//            if (templateArr.count > 0) {
//                for (int i = 0; i<templateArr.count; i++) {
//                    PPTemplateModel *temp = [PPTemplateModel yy_modelWithDictionary:templateArr[i]];
//                    //1. 删除模板对应的上一次生成的 同时 //绑定模板对应相册
//                    
//                    if([temp.eBookTemplateId isEqualToString:templateModel.eBookTemplateId]){
//                        PPEbookAlbum *ebookM = [[PPEbookAlbum alloc] init];
//                        ebookM.albumID = self.normalAlbumModel.albumID;
//                        ebookM.downloadType = PPTemplateDownLoadTypeEmploy;
//                        if(!temp.albums){
//                            temp.albums = [NSMutableArray array];
//                        }
//                        self.shareTemplateModel.coverImgString = temp.coverImgString;
//                        templateModel.coverImgString = temp.coverImgString;
//                        [temp.albums addObject:[ebookM yy_modelToJSONObject]];
//                        
//                        [templateArr replaceObjectAtIndex:i withObject:[temp yy_modelToJSONObject]];
//                        
//                    }else{
//                        for (NSDictionary *albumDict in temp.albums) {
//                            PPEbookAlbum *ebookT = [PPEbookAlbum yy_modelWithDictionary:albumDict];
//                            if (ebookT.albumID == self.albumM.albumID) {
//                                [temp.albums removeObject:albumDict];
//                                
//                                [templateArr replaceObjectAtIndex:i withObject:[temp yy_modelToJSONObject]];
//                                break;
//                            }
//                        }
//                    }
//                }
//                [templateArr writeToFile:kTemplatePlist atomically:YES];
//            }
//            
//
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//                if (templateModel.orderNum == 0) {
//                    [self.normalAlbumModel.ebookPictures removeAllObjects];
//                    self.shareTemplateType = PPShareViewTypeNone;
//                    [self setShareCoverInfo];
//                }else{
//                    self.shareTemplateType = PPShareTemplateTypeEbook;
//                    self.normalAlbumModel.ebookPictures = tempEbookPics;
//                    self.eBookTemplateModel = templateModel;
//                     [self setShareCoverInfo];
//                }
//            });
//            
//        }else{
//            PPLog(@"电子相册生成失败 = %@",error);
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//            self.updateEbook = NO;
//            
//            [self hiddenPrgoress];
//            
//            [self.navigationController.view toastMessage:@"电子相册生成失败,请重试！" duration:1.f];
//        }
//        PPLog(@"%@",kTemplatePlist);
//    }];

    
    

    
    
    
}
#pragma mark - 生成电子书对应模板(1)
- (void)templateViewController1:(PPTemplateViewController *)templateVc employEbooktemplateModel:(PPTemplateModel *)templateModel{
    
    //1、之前逻辑 每套用一次模板就重新生成 （上传图片、更改为之前拿相册里面的图片）
    //2、修改电子书 没次修改上传图片 替换掉之前图片
    
    self.updateEbook = YES;
    
//-    self.albumModel.image = self.coverImage;
    
    self.albumpictureIds = [NSMutableArray array];
    
    if (self.albumpictureIdsOrg.count>0) {
        
        for (id picId in self.albumpictureIdsOrg) {
            [self.albumpictureIds addObject:picId];
        }
    }
    
    
    self.albumpictureURLs = [NSMutableArray array];
    
    if (self.albumpictureURLsOrg.count>0) {
        
        for (NSString *picUrl in self.albumpictureURLsOrg) {
            [self.albumpictureURLs addObject:picUrl];
        }
    }
    
    self.ebookImages = [NSMutableArray array];
    
    if (self.ebookImagesOrg.count>0) {
        for (UIImage *pic in self.ebookImagesOrg) {
            [self.ebookImages addObject:pic];
        }
    }
    
    
    if (!self.albumpictureIds || !self.albumpictureURLs || !self.ebookImages ) {
        
        [self.navigationController.view toastMessage:@"网络状况不好~稍后再试！"];

        return;
    }

    self.shareTemplateModel.coverFrameM.coverModel.image = self.ebookImages.firstObject;
    //---------
    if (!self.picFinish) {
        
        [self.navigationController.view toastMessage:@"相册信息正在获取，稍后再试！"];
        return;
    }
    
    
    self.isProgress = YES;
    
    if (templateModel.orderNum == 0) {
        self.shareTemplateType = PPShareViewTypeNone;
    }else{
        self.shareTemplateType = PPShareTemplateTypeEbook;
    }
    self.shareTemplateModel = templateModel;
    //进度条
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self progressViewCreate];
    });
    
    if (self.ebookImages.count > 0) {
        //获取七牛路径
        [self createPicpathWithuuids:self.albumpictureIds templateModel:templateModel uploadImages:self.ebookImages update:true];
    }else{
    
        [self downAllAlbumImage:YES];
    }
    
    
}
///MARK:生成七牛路径
- (void)createPicpathWithuuids:(NSArray *)uuids templateModel:(PPTemplateModel *)tempM uploadImages:(NSMutableArray *)uploadImages update:(BOOL)update{

    
    NSMutableArray *paths = [NSMutableArray array];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setSafeObject:@([DGCurrentAccount.userID longLongValue]) forKey:@"user"];
    [params setSafeObject:uuids forKey:@"pictureId"];
     
    
    [PPNetworkService createEbookPicpathWithparams:params callback:^(id data, NSError *error) {
         PPLog(@"七牛path =  %@",data);
        
        NSArray *res = (NSArray *)data;
        if (res.count > 0) {
            for (int i = 0; i<res.count; i++) {
                PPUploaderFile *uploadFile = [PPUploaderFile yy_modelWithDictionary:res[i]];
                uploadFile.image = uploadImages[i];
                [paths addObject:uploadFile];
            }
        }
        
        if (paths.count > 0) {
            //    3.回调获取七牛路径 上传图片到七牛
            [[PPAlbumManager sharedInstance] uploadEbookPicResults:paths completion:^(NSError *error) {
                PPLog(@"七牛上传了图片error = %@",error);
                  [self createEbookAlbumsPath:paths templateModel:tempM update:update];
            }];
        }
        
    }];
}

///MARK：生成电子书
- (void)createEbookAlbumsPath:(NSMutableArray *)paths templateModel:(PPTemplateModel *)tempM update:(BOOL)update{
    
    NSMutableArray *pics = [NSMutableArray array];
    for (int i = 0; i<paths.count; i++) {
        PPUploaderFile *file = paths[i];
        NSDictionary *dict = @{
                               @"pictureId":file.pictureId,
                               @"url":file.path,
                               @"picType":i==0?@(1):@(2),
                               };
            [pics addObject:dict];
    }

    NSDictionary *ebookDic = @{
                               @"addOrUpdateTemplate":@(update),
                               @"templateId":tempM.eBookTemplateId,
                               @"pics":pics,
                               };
    
    
    [PPNetworkService updateEbookTemplateWithparams:ebookDic callback:^(id data, NSError *error) {
        if (!error) {
            PPLog(@"电子相册生成成功 %@",ebookDic);
//            NSMutableArray *templateArr = [NSMutableArray arrayWithContentsOfFile:kTemplatePlist];
            NSMutableArray *templateArr = [NSKeyedUnarchiver unarchiveObjectWithFile:kTemplatePlist];
            
            if (templateArr.count > 0) {
                for (int i = 0; i<templateArr.count; i++) {
                    PPTemplateModel *temp = templateArr[i];
//                    [PPTemplateModel yy_modelWithDictionary:templateArr[i]];
                    //1. 删除模板对应的上一次生成的 同时 //绑定模板对应相册
                    
                    if([temp.eBookTemplateId isEqualToString:tempM.eBookTemplateId]){
                        PPEbookAlbum *ebookM = [[PPEbookAlbum alloc] init];
                        ebookM.albumID = self.albumM.albumID;
                        ebookM.downloadType = PPTemplateDownLoadTypeEmploy;
                        if(!temp.albums){
                            temp.albums = [NSMutableArray array];
                        }
                        self.shareTemplateModel.coverImgString = temp.coverImgString;
                        [temp.albums addObject:[ebookM yy_modelToJSONObject]];
                        
                        [templateArr replaceObjectAtIndex:i withObject:[temp yy_modelToJSONObject]];

                    }else{
                            for (NSDictionary *albumDict in temp.albums) {
                                PPEbookAlbum *ebookT = [PPEbookAlbum yy_modelWithDictionary:albumDict];
                                if (ebookT.albumID == self.albumM.albumID) {
                                    [temp.albums removeObject:albumDict];
                                    
                                    [templateArr replaceObjectAtIndex:i withObject:[temp yy_modelToJSONObject]];
                                    break;
                                }
                            }
                    }
                }
//                [templateArr writeToFile:kTemplatePlist atomically:YES];
                [NSKeyedArchiver archiveRootObject:templateArr toFile:kTemplatePlist];
            }

        self.shareTemplateModel.coverFrameM.coverModel.image = self.ebookImages.firstObject;
            
        self.eBookModels = [NSMutableArray array];
            
        [self queryEbook];
        
        }else{
            PPLog(@"电子相册生成失败 = %@",error);
            
            self.updateEbook = NO;
            
            [self hiddenPrgoress];
            
            [self.navigationController.view toastMessage:@"电子相册生成失败,请重试！" duration:1.f];
        }
        PPLog(@"%@",kTemplatePlist);
    }];
}

#pragma mark -动画处理
- (void)progressViewCreate{
    self.progressFloat = 0.0f;
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.progressLabel];

    [self.timer resumeTimer];

}
- (void)updateProgress{
    
    int dis = ((arc4random() % 3) + SCREEN_WIDTH * 0.7);
    if (self.progressFloat > 0) {
        dis = self.progressFloat;
    }
    
    CGFloat date = 0.3;
    if ([self.progressLabel.text isEqualToString:@"更新中"]) {
        dis = ((arc4random() % 10) + 10);
    }
    [UIView animateWithDuration:date animations:^{
        CGRect f = self.progressView.frame;
        CGRect labelF = self.progressLabel.frame;
        f.size.width += dis;
        labelF.origin.x += dis;
        self.progressView.frame = f;
        self.progressLabel.frame = labelF;
    }];
    
    
    if (self.updateEbook) {
        
        [self.timer pauseTimer];
        
    }
    
//    if (self.progressView.frame.size.width > SCREEN_WIDTH*0.9 && self.progressView.frame.size.width < SCREEN_WIDTH && self.updateEbook) {
//        
//        [self.timer pauseTimer];
//        
//    }
//
//    
//    if (self.progressView.frame.size.width > SCREEN_WIDTH+dis) {
//        
//        [self hiddenPrgoress];
//        
//        [self createShareView:self.shareTemplateModel];
//        
//        
//        if (self.shareTemplateType == PPShareViewTypeNone) {
//            [self.fullImageView updateCoverImage:self.coverImage];
//        }else{
//            [self.fullImageView updateCoverImage:self.ebookImages.firstObject];
//        }
//        
//    }
}

- (void)hiddenPrgoress{
    [self.timer invalidate];
    self.timer = nil;
    [self.progressView removeFromSuperview];
    [self.progressLabel removeFromSuperview];
    self.progressLabel = nil;
    self.progressView = nil;
    self.isProgress = NO;
    
}
#pragma mark -内页描述更新
- (void)changeAlbumDesc:(NSNotification *)notice{
    
    NSDictionary *dicDesc = notice.object;
    
    if (dicDesc) {
//        NSString *picture = dicDesc[@"pictureid"];
        for (int i = 0; i<self.normalAlbumModel.ebookPictures.count; i++) {
            
            PPPictureModel *picM = self.normalAlbumModel.ebookPictures[i];
//            PPHomeEbookModel *ebookM = self.eBookModels[i];
            if (dicDesc[@"pictureid"] == picM.picID) {
//                ebookM.contentDescription = dicDesc[@"description"];
                picM.picDesc = dicDesc[@"description"];
            }
        }
    }
}

- (void)queryEbook{

    NSDictionary *row = @{@"page":@(1),@"rows":@(1000)};
    
    NSDictionary *dict = @{@"albumId":self.albumM.albumID,
                           @"pageInfo":row,
                           @"order":[self.albumM.order integerValue]==1?@"desc":@"asc",
                           };
    [PPNetworkService gettemplateEbookListWithparams:dict callback:^(id data, NSError *error) {
        self.albumpictureURLs = [NSMutableArray array];
        self.albumpictureIds = [NSMutableArray array];
        PPLog(@"查询到的最新电子书 %@",data);
        NSString *coverURL;
        if (data && [data[@"total"] integerValue]>0) {
            if (data[@"common"]) {
                PPHomeEbookModel *coverM = [PPHomeEbookModel yy_modelWithDictionary:data[@"common"]];
                coverURL = coverM.url;
                coverM.picType = 1;
                [self.eBookModels insertObject:coverM atIndex:0];
                 [self.albumpictureURLs insertObject:coverURL atIndex:0];
                [self.albumpictureIds insertObject:coverM.pictureId atIndex:0];
            }
            
            NSArray *arr = data[@"rows"];
            
            for (NSDictionary *dict in arr) {
                PPHomeEbookModel *ebookM = [PPHomeEbookModel yy_modelWithDictionary:dict];
                ebookM.picType = 2;
                
//                [self.eBookModels addObject:ebookM];
//                [self.albumpictureURLs addObject:ebookM.url];
//                [self.albumpictureIds addObject:ebookM.pictureId];
                
                [self.eBookModels insertObject:ebookM atIndex:1];
                [self.albumpictureURLs insertObject:ebookM.url atIndex:1];
                [self.albumpictureIds insertObject:ebookM.pictureId atIndex:1];
            }

            self.updateEbook = NO;
            
            [self.timer resumeTimer];
            
 
        }
    }];
}

- (void)dealloc{

    [[SDWebImageDownloader sharedDownloader] cancelAllDownloads];
}


//#warning ---查询到了删除的图片？？？？？？
#pragma mark -下载相册的所有图片
- (void)downloadAlbum{

    
//    self.albumpictureIds = [NSMutableArray array];
//    self.albumpictureURLs = [NSMutableArray array];
    
    //        取默认的相册信息
    //        特殊处理 获取相册ID信息 图片id保存
//    NSDictionary *Dict = @{
//                           @"pageInfo":@{@"page":@"1",@"rows":@"100"},
//                           @"albumId":self.albumM.albumID,
//                           };
//    [PPNetworkService queryAlbumPictureids:Dict callback:^(id data, NSError *error) {
//        
//        PPLog(@"------- %@", [data yy_modelToJSONString]);
//        if (!error) {
//            
//            NSArray *arr = data[@"rows"];
//            for (int i = 0; i<arr.count; i++) {
//                NSDictionary *picDic = arr[i];
//                
//                PPLog(@"添加顺序up - %@",[NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",picDic[@"url"]]);
//                //
//                [self.albumpictureIds addObject:picDic[@"pictureId"]];
//                [self.albumpictureURLs addObject:picDic[@"url"]];
//                
//                if([self.albumModel.coverURL isEqualToString:[NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",picDic[@"url"]]]){
//                    PPLog(@"添加顺序Cover - %@",[NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",picDic[@"url"]]);
//                    //封面
//                    [self.albumpictureIds insertObject:picDic[@"pictureId"] atIndex:0];
//                    [self.albumpictureURLs insertObject:picDic[@"url"] atIndex:0];
//                }
//            }
//            
//            if (self.albumpictureURLs.count > 0) {
//                [self downAllAlbumImage:NO];
//            }
//        }
//    }];

    if (self.homeAlbumModel.pictures.count > 0) {
        
        
        [self.homeAlbumModel.pictures enumerateObjectsUsingBlock:^(PPPictureModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [self.self.albumpictureIds addObject:obj.picID];
            [self.self.albumpictureURLs addObject:obj.picURL];
            
        }];
        
        [self downAllAlbumImage:NO];
        
    }
}



#pragma mark -处理原始相册里面的图片信息
- (void)downloadAlbumListOrg{
    self.albumpictureURLsOrg = [NSMutableArray array];
    self.albumpictureIdsOrg = [NSMutableArray array];
    self.ebookImagesOrg = [NSMutableArray array];
    
    if (self.homeAlbumModel.pictures.count > 0) {
        
        
        [self.homeAlbumModel.pictures enumerateObjectsUsingBlock:^(PPPictureModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [self.albumpictureIdsOrg addObject:obj.picID];
            [self.albumpictureURLsOrg addObject:obj.picURL];
            
        }];
        
         [self downAllAlbumImageOrg];
        
    }
    
        //        取默认的相册信息
        //        特殊处理 获取相册ID信息 图片id保存
//        NSDictionary *Dict = @{
//                               @"pageInfo":@{@"page":@"1",@"rows":@"100"},
//                               @"albumId":self.albumM.albumID,
//                               };
//        [PPNetworkService queryAlbumPictureids:Dict callback:^(id data, NSError *error) {
//            
//            if (!error) {
//                
//                NSArray *arr = data[@"rows"];
//                for (int i = 0; i<arr.count; i++) {
//                    NSDictionary *picDic = arr[i];
//                    
//                    PPLog(@"添加顺序up - %@",[NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",picDic[@"url"]]);
//                    //
//                    [self.albumpictureIdsOrg addObject:picDic[@"pictureId"]];
//                    [self.albumpictureURLsOrg addObject:picDic[@"url"]];
//                    
//                    if([self.albumModel.coverURL isEqualToString:[NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",picDic[@"url"]]]){
//                        PPLog(@"添加顺序Cover - %@",[NSString stringWithFormat:@"http://imgtest.pickpic.cc/%@",picDic[@"url"]]);
//                        //封面
//                        [self.albumpictureIdsOrg insertObject:picDic[@"pictureId"] atIndex:0];
//                        [self.albumpictureURLsOrg insertObject:picDic[@"url"] atIndex:0];
//                    }
//                }
//                
//                if (self.albumpictureURLsOrg.count > 0) {
//                    [self downAllAlbumImageOrg];
//                }
//            }
//        }];

}
- (void)downAllAlbumImageOrg{
    
    NSMutableArray *temp = [NSMutableArray array];
    //    //下载所有图片
    dispatch_group_t group =dispatch_group_create();
    for (int i = 0; i <  self.albumpictureURLsOrg.count; i ++)
    {
        PPLog(@"org下载=%@",self.albumpictureURLsOrg[i]);
        
        dispatch_group_enter(group);
        SDWebImageDownloader *manager = [SDWebImageDownloader sharedDownloader];
        manager.maxConcurrentDownloads = 1;
        [manager downloadImageWithURL:[NSURL URLWithString:self.albumpictureURLsOrg[i]] options:SDWebImageDownloaderIgnoreCachedResponse progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            if (image) {
                NSDictionary *dict = @{
                                       @"url":self.albumpictureURLsOrg[i],
                                       @"img":image,
                                    };
                
                [temp addObject:dict];
            }
            PPLog(@"下载完成或失败了,imgs,imgs.count %zd",temp.count);
            if (finished) {
                dispatch_group_leave(group);
            }
        }];
    }
    dispatch_group_notify(group,dispatch_get_main_queue(), ^(){
        if (self.albumpictureURLsOrg.count != temp.count) {
            PPLog(@"图片下载有问题");
            [self downAllAlbumImageOrg];
            return ;
        }
        
        self.picFinish = YES;
        
        for (NSString *strUrl in self.albumpictureURLsOrg) {
            NSString *key = strUrl;
            for (NSDictionary *dict in temp) {
                if ([dict[@"url"] isEqualToString:key]) {
                    PPLog(@"原图片下载%@ - %@",strUrl,dict[@"url"]);
                    [self.ebookImagesOrg addObject:dict[@"img"]];
                    break;
                }
            }
        }
        
    });
    
}
- (void)didReceiveMemoryWarning{

//    [super didReceiveMemoryWarning];
    
    [[SDImageCache sharedImageCache] clearDisk];
    
    [[SDImageCache sharedImageCache] clearMemory];
    
    [[SDWebImageManager sharedManager] cancelAll];
}


- (void)modifyMusicID:(NSString *)musicID musicUrl:(NSString *)musicUrl{
    
    NSInteger albumID = [self.normalAlbumModel.albumID integerValue];
    
    [PPNetworkService musicBindEbookWithparams:@{@"ebook_id":@(albumID),@"music_id":@([musicID longLongValue])} callback:^(id data, NSError *error) {
        if (error == nil) {
            [self deleteFile:[NSString stringWithFormat:@"%zd.mp3",albumID]];
            
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            JCDownloadItem *downloadItem = [[JCDownloadItem alloc] init];
            downloadItem.downloadUrl = musicUrl;
            NSString *songPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%zd.mp3",albumID]];
            
            downloadItem.downloadFilePath = songPath;
            self.operation = [JCDownloadOperation operationWithItem:downloadItem];
          
            [self.operation startWithProgressBlock:^(NSProgress *progress) {
                
                //update progress
            } completionBlock:^(NSURL *filePath, NSError *error) {
                //download operation completion, do something
                
                //                    NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,[NSString stringWithFormat:@"%@.mp3",songM.name]];
                NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,[NSString stringWithFormat:@"%zd.mp3",@(albumID)]];
                PPLog(@"播放地址 = %@",fullPath);

            }];
        }}];
}
-(void)deleteFile:(NSString *)fileName{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        NSLog(@" have");
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        } 
    }
}
@end
